Ext.define('Admin.view.sys.user.InsertFormWinController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.sys_user_insertformwincontroller',

    /*保存按钮事件*/
    onSave: function(){
        Ext.Msg.show({
            title:'提示信息',
            msg: '确定该操作吗?',
            buttons: Ext.Msg.OKCANCEL,
            icon: Ext.Msg.QUESTION,
            fn: this.doSaveRecord,
            scope: this
        });
    },

    /*发送请求*/
    doSaveRecord: function(buttonId) {
        if(buttonId === "ok") {
            var me = this;
            var form = this.lookup("formpanel");
            if(!form.isValid()) {
                return;
            }
            var fileEl = form.down("filefield").fileInputEl.dom;

            //身份token
            var sessionToken = Ext.util.LocalStorage.get('ext').getItem('auth-token');

            var formData = new FormData();

            //添加表单普通数据
            var submitValues = form.getForm().getValues();
            Object.keys(submitValues).forEach(function (key) {
                formData.append(key, submitValues[key]);
            });

            //添加表单文件
            if(fileEl.files[0]) {
                formData.append('file',fileEl.files[0]);
            }

            me.getView().setLoading('数据保存中...');
            fetch(ServerUrl + '/SysUserController/insert', {
                method: 'POST',
                headers: {'auth-token': sessionToken},
                credentials: 'omit',
                body: formData
            })
            .then(response => {
                response.json().then(json => {
                    me.getView().setLoading(false);
                    Ext.popup.Msg('提示信息', json.message);
                    if(json.success) {
                        me.fireEvent('recordAdded');
                        me.getView().close();
                    }
                });
            })
            .catch((error) => {
                Ext.popup.Msg('提示信息', error.message);
                me.getView().setLoading(false);
            });

            // 表单中存在file控件 则ext会使用iframe进行提交，在跨域时获取不到返回值.
            // form.submit({
            //     url: ServerUrl + '/SysUserController/insert',
            //     successHint: true,
            //     success: function() {
            //         me.fireEvent('recordAdded');
            //         me.getView().close();
            //     }
            // });
        }
    },

    /*关闭窗口*/
    onCancel: function() {
        this.getView().close();
    }
});
